<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\ScheduleRequest;
use App\Models\Schedule;
use App\Models\Shop;
use App\Transformers\ScheduleTransformer;
use Illuminate\Http\Request;

class SchedulesController extends Controller
{
    public function index(ScheduleRequest $request)
    {
        $shop_id = $request->get('shop_id');

        if (!$shop_id) {
            $product_ids = $this->user->shop->products->pluck('id');
        } else {
            $shop = Shop::find($shop_id);

            if (!$shop) {
                $this->response->error(trans('api.not_exists'), 200);
            }

            $product_ids = $shop->products->pluck('id');
        }

        $data = Schedule::whereIn('goods_id', $product_ids)->where('goods_type', 'App\Models\Product')->paginate();

        return $this->response->paginator($data, new ScheduleTransformer());
    }

    public function create(ScheduleRequest $request)
    {
        $data = $request->only([
            'goods_id', 'begin_time', 'end_time', 'price',
        ]);

        $data['goods_type'] = 'App\Models\\' . ucfirst($request->get('goods_type'));

        if ($data['begin_time'] >= $data['end_time']) {
            $this->response->error(trans('api.save_failed'), 200);
        }

        $res = Schedule::create($data);

        if ($res) {
            return response()->json(['message' => trans('api.save_succeed'), 'code' => 1, 'status' => true, 'data' => ''], 200);
        } else {
            return response()->json(['message' => trans('api.save_failed'), 'code' => 0, 'status' => false], 200);
        }
    }

    public function edit(ScheduleRequest $request)
    {
        $id = $request->get('id');

        $data = $request->only([
            'begin_time', 'end_time', 'price',
        ]);

        $schedule = Schedule::find($id);

        if ($schedule->status == 1) {
            return response()->json(['message' => trans('api.schedule_is_occupied'), 'code' => 0, 'status' => false], 200);
        }

        $res = $schedule->update($data);

        if ($res) {
            return response()->json(['message' => trans('api.update_succeed'), 'code' => 1, 'status' => true, 'data' => ''], 200);
        } else {
            return response()->json(['message' => trans('api.update_failed'), 'code' => 0, 'status' => false], 200);
        }
    }

    public function destroy(ScheduleRequest $request)
    {
        $id = $request->get('id');

        $res = Schedule::destroy($id);

        if ($res) {
            return response()->json(['message' => trans('api.delete_succeed'), 'code' => 1, 'status' => true, 'data' => ''], 200);
        } else {
            return response()->json(['message' => trans('api.delete_failed'), 'code' => 0, 'status' => false], 200);
        }
    }

}
